/*
* 图片选择组件
*
*
* */
import 'dart:async';
import 'package:center_beijing/common/styles.dart';
import 'package:center_beijing/widgets/photo_view_gallery.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:flutter/cupertino.dart';
import 'dart:io';
import "package:images_picker/images_picker.dart";
import 'package:get/get.dart';

class ImageSelectWidget extends StatefulWidget {
  final Function onchange;
  final bool haveVideo;
  final int maxNumber;
   ImageSelectWidget({@required this.onchange,this.haveVideo=false,this.maxNumber=6});
  @override
  _ImageSelectWidgetState createState() => _ImageSelectWidgetState();
}

class _ImageSelectWidgetState extends State<ImageSelectWidget> with SingleTickerProviderStateMixin {
  AnimationController _controller;
  List allList = [1];
  List<Media> photos2 = [];
  bool isDisplayingDetail = true;
  @override
  void initState() {
    _controller = AnimationController(vsync: this);
    super.initState();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  List<Widget> getWidgetList() {
    return allList
        .asMap()
        .keys
        .map((index) => getItemContainer(index))
        .toList();
  }

  Widget getItemContainer(index) {
    if (photos2.length<widget.maxNumber&&index == allList.length - 1) {
      return GestureDetector(
        onTap: () => _handleTap(),
        child: Container(
          padding: EdgeInsets.all(Styles.spacing16),
          child: Image(
            image: AssetImage('assets/images/btn_addpic.png'),
            width: 50,
            height: 50,
            fit: BoxFit.fill,
          ),
        ),
      );
    } else {
      return Padding(
        padding: const EdgeInsets.symmetric(
          horizontal: 15.0,
          vertical: 17.0,
        ),
        child: AspectRatio(
          aspectRatio: 1.0,
          child: Stack(
            children: <Widget>[
              Positioned.fill(child: _selectedAssetWidget(index)),
              AnimatedPositioned(
                duration: kThemeAnimationDuration,
                top: isDisplayingDetail ? 2.0 : -30.0,
                right: isDisplayingDetail ? 2.0 : -30.0,
                child: _selectedAssetDeleteButton(index),
              ),
            ],
          ),
        ),
      );
    }
  }
  Widget _selectedAssetWidget(int index) {
    final Media asset = photos2.elementAt(index);
    return GestureDetector(
      onTap: isDisplayingDetail
          ? () async {
        if(asset.path.split('.').last=='mp4'){
          // Navigator.pushNamed(context, 'vedio_preview_page',
          //     arguments: asset.path+'&&'+'2');
        }else{
          Navigator.of(context).push(new FadeRoute(
              page: PhotoViewGalleryScreen(
                  local:false,
                  images: photos2, //传入图片list
                  index: index, //传入当前点击的图片的index
                  heroTag: '')));
        }
      }
          : null,
      child: RepaintBoundary(
        child: ClipRRect(
          borderRadius: BorderRadius.circular(8.0),
          child: _assetWidgetBuilder(asset),
        ),
      ),
    );
  }

  Widget _assetWidgetBuilder(Media asset) {
    Widget widget;
    widget = _imageAssetWidget(asset);
    return widget;
  }
  Widget _imageAssetWidget(Media asset) {
    return Image.file(File(asset.thumbPath),fit: BoxFit.fill);
  }
  Widget _selectedAssetDeleteButton(int index) {
    return GestureDetector(
      onTap: () => removeAsset(index),
      child: DecoratedBox(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(4.0),
          color: Colors.grey,
        ),
        child: Icon(
          Icons.close,
          color: Colors.white,
          size: 18.0,
        ),
      ),
    );
  }

  void removeAsset(int index) {
    setState(() {
      allList.removeAt(index);
      photos2.removeAt(index);
      if(photos2.length==widget.maxNumber-1){
        allList.add(1);
      }
      if (allList.isEmpty) {
        isDisplayingDetail = false;
      }
      widget.onchange(photos2);
    });
  }
  Future getImage() async {
    List<Media> res = await ImagesPicker.pick(
      maxSize:1000,
      quality: 0.6,
      count: widget.maxNumber-photos2.length,
      pickType: PickType.image,
      gif: false,
    );
    print(res);
    if(res!=null){
      if((photos2.length+res.length)<=widget.maxNumber){
        this.setState(() {
          allList.insertAll(0,res);
          photos2.insertAll(0,res);
          if(photos2.length==widget.maxNumber){
            allList.removeLast();
          }
        });
      }else{
        var tem = res.getRange(0, widget.maxNumber-photos2.length);
        this.setState(() {
          allList.insertAll(0,tem);
          photos2.insertAll(0,tem);
          if(photos2.length==widget.maxNumber){
            allList.removeLast();
          }
        });
        Fluttertoast.showToast(msg: '照片最大可传'+widget.maxNumber.toString()+'张');
      }
      widget.onchange(photos2);
    }

  }
  Future getVideo() async {
    List<Media> res = await ImagesPicker.pick(
      count: 1,
      pickType: PickType.video,
      gif: false,
    );
    if(res!=null){
      if((photos2.length+res.length)<=widget.maxNumber){
        this.setState(() {
          allList.insertAll(0,res);
          photos2.insertAll(0,res);
          if(photos2.length==widget.maxNumber){
            allList.removeLast();
          }
        });
      }else{
        var tem = res.getRange(0, widget.maxNumber-photos2.length);
        this.setState(() {
          allList.insertAll(0,tem);
          photos2.insertAll(0,tem);
          if(photos2.length==widget.maxNumber){
            allList.removeLast();
          }
        });
        Fluttertoast.showToast(msg: '照片最大可传'+widget.maxNumber.toString()+'张');
      }
      widget.onchange(photos2);
    }
  }
  Future getCamera() async {
    List<Media> res = await ImagesPicker.openCamera(
      pickType: PickType.image,
      maxSize:1000,
      quality: 0.6,
    );
    print(res);
    if(res!=null){
      if((photos2.length+res.length)<=widget.maxNumber){
        this.setState(() {
          allList.insertAll(0,res);
          photos2.insertAll(0,res);
          if(photos2.length==widget.maxNumber){
            allList.removeLast();
          }
        });
      }else{
        var tem = res.getRange(0, widget.maxNumber-photos2.length);
        this.setState(() {
          allList.insertAll(0,tem);
          photos2.insertAll(0,tem);
          if(photos2.length==widget.maxNumber){
            allList.removeLast();
          }
        });
        Fluttertoast.showToast(msg: '照片最大可传'+widget.maxNumber.toString()+'张');
      }
      widget.onchange(photos2);
    }
  }

  // 从底部弹出CupertinoActionSheet使用showCupertinoModalPopup
  void _handleTap() { // 某个GestureDetector的事件
    FocusScope.of(context).requestFocus(FocusNode());
    showCupertinoModalPopup(
      context: context,
      builder: (BuildContext context) => actionSheet(context),
    ).then((value) {
      CupertinoModalPopupRoute bbq = value;
    });
  }

  // 底部弹出菜单actionSheet
  Widget actionSheet(BuildContext context) {
    return new CupertinoActionSheet(
      actions: <Widget>[
        CupertinoActionSheetAction(
          child: const Text(
            '打开相机拍照',
            style: TextStyle(
              fontSize: 14.0,
              fontFamily: 'PingFangRegular',
            ),
          ),
          onPressed: () {
            // 打开相机拍照
            getCamera();
            Navigator.pop(context);
          },
        ),
        widget.haveVideo?CupertinoActionSheetAction(
          child: const Text(
            '视频选择',
            style: TextStyle(
              fontSize: 14.0,
              fontFamily: 'PingFangRegular',
            ),
          ),
          onPressed: () {
            // 打开相册，选取照片
            getVideo();
            // 关闭菜单
            Navigator.pop(context);

          },
        ):Container(),
        CupertinoActionSheetAction(
          child: const Text(
            '图片选择',
            style: TextStyle(
              fontSize: 14.0,
              fontFamily: 'PingFangRegular',
            ),
          ),
          onPressed: () {
            // 打开相册，选取照片
            getImage();
            Navigator.pop(context);
          },
        ),

      ],
      cancelButton: CupertinoActionSheetAction(
        child: new Text(
          '取消',
          style: TextStyle(
            fontSize: 13.0,
            fontFamily: 'PingFangRegular',
            color: const Color(0xFF666666),
          ),
        ),
        onPressed: () {
          // 关闭菜单
          Navigator.pop(context);
        },
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return widget.maxNumber>0?Container(
      padding: EdgeInsets.fromLTRB(0, 0, 0, 0),
      child: GridView.count(
        physics: const NeverScrollableScrollPhysics(),
        shrinkWrap: true,
        //水平子Widget之间间距
        crossAxisSpacing: 10.0,
        //垂直子Widget之间间距
        mainAxisSpacing: 0.0,
        //GridView内边距
        padding: EdgeInsets.all(5.0),
        //一行的Widget数量
        crossAxisCount: 3,
        //子Widget宽高比例
        childAspectRatio: 1,
        //子Widget列表
        children: this.getWidgetList(),
      ),
    ):Container();
  }
}

class FadeRoute extends PageRouteBuilder {
  final Widget page;

  FadeRoute({this.page})
      : super(
    pageBuilder: (
        BuildContext context,
        Animation<double> animation,
        Animation<double> secondaryAnimation,
        ) =>
    page,
    transitionsBuilder: (
        BuildContext context,
        Animation<double> animation,
        Animation<double> secondaryAnimation,
        Widget child,
        ) =>
        FadeTransition(
          opacity: animation,
          child: child,
        ),
  );
}
